import * as React from "react";

// [Persisting State Between Component Mounts in React](https://codewithstyle.info/use-persisted-state/)
const Store = new Map<string, unknown>();

export const usePersistedState = <S>(
  id: string,
  initialState: S | (() => S),
) => {
  const stateFromStore = Store.has(id) ? (Store.get(id) as S) : undefined;
  const [state, dispatch] = React.useState<S>(stateFromStore ?? initialState);
  React.useEffect(() => {
    Store.set(id, state);
  }, [state, id]);
  return [state, dispatch] as const;
};

export const removeFromState = (id: string) => {
  Store.delete(id);
};
